package com.example;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Description: Bio通信的服务端
 * @Author: kangyang
 * @DateTime: 2024/10/23 15:57
 **/
public class Server {

    public static void main(String[] args) throws IOException {
        // 服务端启动必备
        ServerSocket serverSocket = new ServerSocket();
        // 表示服务端在哪个端口监听
        serverSocket.bind(new InetSocketAddress(8888));
        System.out.println("服务端启动了");
        try {
            while (true) {
                Socket socket = serverSocket.accept();
                new Thread(new ServerTask(socket)).start();
            }
        } finally {
            serverSocket.close();
        }
    }


    //每个和客户端的通信都会打包成一个任务，交个一个线程来执行
    private static class ServerTask implements Runnable {

        private Socket socket;

        public ServerTask(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            // 实例化与客户端通信的输入输出流
            try {
                ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());
                ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());

                // 接收客户端的输出，也就是服务端的输入
                String userName = inputStream.readUTF();
                System.out.println("Accept client message:" + userName);

                Thread.sleep(1000000);

                // 服务器的输出，也就是客户端的输入
                outputStream.writeUTF("hello " + userName);
                outputStream.flush();
            } catch (IOException e) {
                throw new RuntimeException(e);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                try {
                    socket.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
